package com.qf.controller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.qf.entity.HappyBeanHistory;
import com.qf.entity.RechargeOrder;
import com.qf.service.HappyBeanHistoryService;
import com.qf.service.IUserService;
import com.qf.service.RechargeOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@CrossOrigin
@RestController
public class RechargeOrderController {

    @Autowired
    private RechargeOrderService rechargeOrderService;
    @Autowired
    private HappyBeanHistoryService happyBeanHistoryService;
    @Autowired
    private IUserService userService;

    @RequestMapping("/order/create")
    public String createOrder(Integer uid, double money) {
        String orderid = UUID.randomUUID().toString();

        //double Integer->BitDecimal
        BigDecimal moneyBD = BigDecimal.valueOf(money);
        BigDecimal numberBD = BigDecimal.valueOf(100);
        //创建订单对象
        RechargeOrder rechargeOrder = new RechargeOrder();
        rechargeOrder.setuId(uid);//下单用户id
        rechargeOrder.setMoney(moneyBD);//下单的金额
        rechargeOrder.setOrderId(orderid);//订单号
        rechargeOrder.setStatus(0);//未支付
        rechargeOrder.setCreateTime(new Date());//下的那时间
        rechargeOrder.setBeanNumber(moneyBD.multiply(numberBD).intValue());//充值欢乐豆数量
//添加订单
        rechargeOrderService.insertOrder(rechargeOrder);
        return orderid;
    }

    //查询订单列表，根据用户id
    @RequestMapping("/order/list")
    public List<RechargeOrder> queryList(Integer uid) {
        return rechargeOrderService.queryRechargeOrderByUid(uid);
    }

    //订单支付接口
    @RequestMapping("/order/pay")
    public void orderPay(String orderid, HttpServletResponse response) throws IOException {
        System.out.println("接收到支付宝的订单" + orderid);
        //
        //通过订单号查询订单信息
        RechargeOrder order = rechargeOrderService.getByOrderId(orderid);
        //调用支付宝进行支付
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",//沙箱环境地址
                "2021000118679395",//APPID
                "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDGI1T3gglk0ssg7e1MJoeRz03f9eJJa1wixKftfRSEQ6cfBkCDLSiod5LGc4XXa6s4SQ8M/sbD7nir5Oahjtfq9Dp9sqfQN6kkVJwITRRhiFRBcWVTEipNU6e7jp6CSk0nSJ9xevixfH6/vhvc8aPWOl2seiDwL3b3+uDkV/3puFm34Fn497g2IZLdECOAwSnyF7wfzt/tewgl5r2bSZUg7zTuy5ms4Dwc9vIOD1om/hb6QJM1Q70tezh1r0XXUSH1ey9ca/P8hQe2E4lnt3judNV0umC0jesRgwn3Lj4W6SvtZHzjztqxk56uB+S9yl4WLd7VSUd2huJWWIWeaJvpAgMBAAECggEBALzUS1Oe0EkQQ5pcZjyes7EYekUo1sHV2XchKFFDVVxABXOhx7W8QfVcD7uluTZ2XDVGG1vtK4zrJoHbopjxw4EdxOiqbRgZE8+V+yZGH1hcTsAXy9MBiuMrCL3My++r1B/OLHZAFedAmKMwEOneOKAf+8o2klGVSrJGnDHCUjB8XDHr3gIoWTEIbPo89SVarmqxbCWcCbxyGONbMttVI5N1+Wg7NwgsZxR9/iJNr1hFwLjwFo4JZktKMhZllEKdNKjiSsjT/2BAC1sUxs1ZTFxRe0p+WnYaxqHT2I4+gr9YFm6MwT75EjteFn+dnJvuqp4hIxig6UkWSWdtwGPVpAkCgYEA8uyLSgfGqcXNDIN4BMO0mGx85+2pu7KMvpipVcGvswfuPznpW8PS+A5wcAiJDVeuBqYa+5VybOPj7ySLLZ4BRZnVF/6esCyo9n2Vdzy/UzaqeuzsdURLq4CicT44aqd/8BTUjDYrpFbOK2F/Ur4m2VCOXMA8z/TS+D0XwtlNhYcCgYEA0M2kyqHSZwYK9/CssK1s495Ro1nUFlVcOhGhGD3n5Sk8lbzMzNg5gsfI44WDV5kQucr/y6+nyJ/C29QfRZR0PHDNe05MECiPHm4xnQAWdoGGCYXWo06Hdw1pc9EjdzBxTRD5ABDsqk55RYAtZY22dfjiEzhWxPcE4y5dcdRWLw8CgYBbLixOGkMYQFVpyAMJjse/mqD7kPpvqGIpvDV7KdsgEO79LmiH+CW80/aiJqICrxF0D277VaoAcz1/6rCO68rAbDBO9FRt/iVhd9vdSKDrxA4TW9CZZ4wbkInohZk5dyuPWtI42rBg2/BA2jSnQxZj5Ve6OrHYwKVbZdsAWP4/CwKBgA0fj6boqses2o2gw8nK7JgZxfnFUI4iyUwhBYX3hhaiE9u5ZQnO4TZ2Bgs+vfWIekOjHZaYsKvsVpvoZhrCbNfLoy6HykINuokIFfgvJDpIg7sffVEAQ4VZA3KzB06bbdORKIU3ixhdHEQg/TlvwbMCdHsOxG1WtSjuJhNcbBpDAoGBAOWRXPTIh5JTv9idYoiLilbokuACU0PNLE6aBI1L212kFUvCP+WiJA5M+9dNzhwtmEjG6TgrMNQrtlJNTMAmKJ+vzjGZTvIb0twQppS6DozWNyCyos34fdLMB1ljtfwaUbB774rLCygRpHEZUTQNG5dNBk/DCR3eGSgy0K+ByGlp",//数据格式
                "json",
                "utf-8",//编码
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmxM8H4rFHt7bFmwClsQWgbnlu6Z3t4QOztqSyx3P3bjaa7K7AnKR3VQv+Yrqu0PIgSq3K/sWtUbHrG0yn7k3dcQlySq1w53TkA0sNs2YuMvLh1AuXGvmCNYs0dAmCMINg3rO+T/JV8vjWMiTWdBDn/6fmt7M73W2IpKTzv3m5c4HuYPv8LUYaA4kF8Vn1FiJcd37ltxUxbfUUZEZ4lD0gQu2+jK6gMXYP1gnrqjuBFLEz6RHTCWulKAOdbwK1XX+7+c60SsimPM8zjHhR2MNagtNdQPjcKINJD9NlW4LmkYVLxFupbTUKeFiOf6PfRhTznlJPPiFLA7PdhS7BUOhwwIDAQAB",
                "RSA2");//非对称加密算法RSA
        //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl("http://www.baidu.com/");//同步请求
        alipayRequest.setNotifyUrl("http://localhost:8080/pay/result"); //异步请求，在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":\"" + order.getOrderId() + "\"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":" + order.getMoney().doubleValue() + "," +
                "    \"subject\":\"欢乐豆" + order.getBeanNumber() + "个\"" +
                "  }"); //填充业务参数
        String form = "";
        try {
            //发送支付请求，调用支付宝服务器返回一个支付的HTML页面
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form); //直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();


    }

    //支付宝支付后的异步回调接口
    @RequestMapping("/pay/query")
    public int payResult(String orderid) throws AlipayApiException {
        //发请求给支付宝查订单交易结果
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",//沙箱环境地址
                "2021000118679395",//APPID
                "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDGI1T3gglk0ssg7e1MJoeRz03f9eJJa1wixKftfRSEQ6cfBkCDLSiod5LGc4XXa6s4SQ8M/sbD7nir5Oahjtfq9Dp9sqfQN6kkVJwITRRhiFRBcWVTEipNU6e7jp6CSk0nSJ9xevixfH6/vhvc8aPWOl2seiDwL3b3+uDkV/3puFm34Fn497g2IZLdECOAwSnyF7wfzt/tewgl5r2bSZUg7zTuy5ms4Dwc9vIOD1om/hb6QJM1Q70tezh1r0XXUS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JDpIg7sffVEAQ4VZA3KzB06bbdORKIU3ixhdHEQg/TlvwbMCdHsOxG1WtSjuJhNcbBpDAoGBAOWRXPTIh5JTv9idYoiLilbokuACU0PNLE6aBI1L212kFUvCP+WiJA5M+9dNzhwtmEjG6TgrMNQrtlJNTMAmKJ+vzjGZTvIb0twQppS6DozWNyCyos34fdLMB1ljtfwaUbB774rLCygRpHEZUTQNG5dNBk/DCR3eGSgy0K+ByGlp",//数据格式
                "json",
                "utf-8",//编码
                "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmxM8H4rFHt7bFmwClsQWgbnlu6Z3t4QOztqSyx3P3bjaa7K7AnKR3VQv+Yrqu0PIgSq3K/sWtUbHrG0yn7k3dcQlySq1w53TkA0sNs2YuMvLh1AuXGvmCNYs0dAmCMINg3rO+T/JV8vjWMiTWdBDn/6fmt7M73W2IpKTzv3m5c4HuYPv8LUYaA4kF8Vn1FiJcd37ltxUxbfUUZEZ4lD0gQu2+jK6gMXYP1gnrqjuBFLEz6RHTCWulKAOdbwK1XX+7+c60SsimPM8zjHhR2MNagtNdQPjcKINJD9NlW4LmkYVLxFupbTUKeFiOf6PfRhTznlJPPiFLA7PdhS7BUOhwwIDAQAB",
                "RSA2");//非对称加密算法RSA
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", orderid);
        request.setBizContent(bizContent.toString());
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        if (response.isSuccess()) {
            System.out.println("调用成功");
            //判断支付结果
            String tradeStatus = response.getTradeStatus();
            if (tradeStatus.equals("TRADE_SUCCESS")) {
                //支付成功
                System.out.println("支付成功");
                //根据
                RechargeOrder order = rechargeOrderService.getByOrderId(orderid);
                //修改订单状态
                rechargeOrderService.updateOrderStatus(orderid, 1);
                //生成积分流水记录
                HappyBeanHistory happyBeanHistory = new HappyBeanHistory();
                happyBeanHistory.setuId(order.getuId());//欢乐豆所属用户
                happyBeanHistory.setBeanNumber(order.getBeanNumber());
                happyBeanHistory.setType(0);//增加
                happyBeanHistory.setSource(0);//欢乐豆来源
                happyBeanHistory.setCreateTime(new Date());
                happyBeanHistoryService.insertHistory(happyBeanHistory);
                //给用户设置欢乐豆
                int newHappyBean = userService.addHappyBean(order.getuId(), order.getBeanNumber());
                return newHappyBean;
            }
        } else {
            System.out.println("调用失败");
        }
        return -1;

    }

}
